/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.matezk.dms.things.service.impl;

import cn.matezk.dms.things.mapper.SceneActionMapper;
import cn.matezk.dms.things.mapper.TimerSceneMapper;
import cn.matezk.dms.things.model.entity.SceneActionDO;
import cn.matezk.dms.things.model.entity.TimerSceneDO;
import cn.matezk.dms.things.model.query.TimerSceneQuery;
import cn.matezk.dms.things.model.req.TimerSceneReq;
import cn.matezk.dms.things.model.resp.TimerSceneDetailResp;
import cn.matezk.dms.things.model.resp.TimerSceneResp;
import cn.matezk.dms.things.service.TimerSceneService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.continew.starter.extension.crud.service.impl.BaseServiceImpl;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 定时场景业务实现
 *
 * @author 程道林
 * @since 2025/08/28 22:10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TimerSceneServiceImpl extends BaseServiceImpl<TimerSceneMapper, TimerSceneDO, TimerSceneResp, TimerSceneDetailResp, TimerSceneQuery, TimerSceneReq> implements TimerSceneService {
    private TimerSceneMapper timerSceneMapper;
    private SceneActionMapper sceneActionMapper;

    @Override
    @Transactional
    public Long add(TimerSceneReq req) {
        Long sceneId = super.add(req);
        AtomicInteger step = new AtomicInteger(1);
        req.getActions().forEach(action -> action.setStep(step.getAndIncrement()));
        sceneActionMapper.insertBatch(req.getActions());
        return sceneId;
    }

    @Override
    public TimerSceneDetailResp get(Long id) {
        TimerSceneDetailResp resp = super.get(id);
        List<SceneActionDO> actions = sceneActionMapper.selectBySceneId(id);
        resp.setActions(actions);
        return resp;
    }

    @Override
    @Transactional
    public void update(TimerSceneReq req, Long id) {
        super.update(req, id);
        sceneActionMapper.deleteBySceneId(id);
        sceneActionMapper.insertBatch(req.getActions());
    }

    @Override
    public void delete(List<Long> ids) {
        super.delete(ids);
        ids.forEach(id -> {
            sceneActionMapper.deleteBySceneId(id);
        });
    }
}